package com.kokomi.listener;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kokomi.pojo.Item;
import com.kokomi.pojo.Order;
import com.kokomi.pojo.RedisConst;
import com.kokomi.service.ItemService;
import com.kokomi.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.messaging.handler.annotation.Header;

import java.util.List;

/**
 * 监听超时未支付的订单
 */
@Component
@RabbitListener(queues = "order.dlx.queue")
@Slf4j
public class OrderStatusListener {


    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ItemService itemService;

    @SneakyThrows
    @RabbitHandler
    public void handler(Order order, Message message, Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) {
        log.info("监听到超时未支付的订单，订单号：{}", order.getOrderNum());
        Order orderTemp = orderService.getById(order.getId());
        if (orderTemp.getState() != 2) {

            // 修改订单状态为超时未支付
            orderTemp.setState(7);
            orderService.updateById(orderTemp);
            log.info("订单状态修改为超时未支付");
        }

        // 还原redis预扣除的库存
        Long orderId = order.getId();
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<Item> list = itemService.list(queryWrapper);
        for (Item item : list) {
            Long bookId = item.getBookId();

            redisTemplate.opsForHash().increment(RedisConst.BOOK_STORAGE, bookId.toString(), item.getBuyCount());
        }
        log.info("订单超时未支付，库存已还原");

        // 处理订单超时未支付的逻辑
        channel.basicAck(deliveryTag, false);

    }


}
